package com.sheng.util;

import com.sheng.po.jmeter.JmeterPathPo;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @Author: 王胜
 * @Date 2022/12/1 22:44
 */
@Slf4j
public class JmeterUtil {
    public static void main(String args[]) {
//        String t = "D:\\back_code\\uploadJemter\\车企管理平台V1_0715.jmx(2022-12-02)\\@车企管理平台V1_0715.jmx";
//        windowsRun(t);
    }

    public static String  windowsRun(JmeterPathPo jmeterPath) {
        Runtime runtime = Runtime.getRuntime();
        String  JmeterPath = jmeterPath.getJmeterPath();
        String filePath = JmeterPath.substring(0, JmeterPath.indexOf("@"));
        log.info("文件路径为:{}", filePath);
        String resultPath = filePath + "\\result";
        String reportPath = filePath + "\\report";

        log.info("结果文件路径为：{}", filePath);
        log.info("报告文件路径为：{}", reportPath);

        String command = "D:\\jmeter\\apache-jmeter-5.4.2\\bin\\jmeter.bat -n -t " + JmeterPath + " -l " + filePath + "\\result\\jmeterResult.jtl  -e -o " + filePath + "\\report";
        log.info("命令行为:{}", command);


        try {

            File resultFile = new File(resultPath);
            File reportFile = new File(reportPath);
            if (resultFile.exists() && reportFile.exists()) {
                log.info("相关报关文件存在");
                deleteFile(resultFile);
                deleteFile(reportFile);
                log.info("报告相关文件被删除");
            }


            Process process = runtime.exec(command);
            log.info("------------------WinCmdRunning()--------------------");
            //取得命令结果的输出流
            InputStream fis = process.getInputStream();
            //用一个读输出流类去读
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String line = null;
            //逐行读取输出到控制台
            while ((line = br.readLine()) != null) {
                log.info(line);
            }
            String[] split = JmeterPath.split("/");
            String folderName = split[3];
            String reportHtml = "http://localhost:9090/jmeterReport/" + folderName + "/report/index.html";
            log.info("报告url路径:{}",reportHtml);
            return reportHtml;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //    删除文件方法
    public static void deleteFile(File file) {
        //判断文件不为null或文件目录不存在
        if (file == null || !file.exists()) {
            log.info("文件删除失败,请检查文件路径是否正确");
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //打印文件名
//            String name = file.getName();
//            System.out.println(name);
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                deleteFile(f);
            } else {
                f.delete();
            }
        }
        //删除空文件夹  for循环已经把上一层节点的目录清空。
        file.delete();
    }

}
